﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Console = Colorful.Console;
using Utils;
namespace Server
{
    class Program
    {
        static void GetPort()
        {
            Console.Write("Please enter PORT to listen(0-65535): ");
            Config.WritePrivateProfileString("Server", "Port", Console.ReadLine(), @".\config.ini");
        }
        static ushort Port = 23333;

        static void Display(string ip)
        {
            Console.Write("[");
            Console.Write(DateTime.Now.ToLongTimeString(), Color.FromArgb(0, 255, 0));
            Console.Write("] ");
            Console.WriteLine(ip);
        }
        static private void Listen()
        {
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, Port));

            //不断监听端口
            while (true)
            {
                listener.Listen(0);
                Socket socket = listener.Accept();
                NetworkStream ntwStream = new NetworkStream(socket);
                StreamReader strmReader = new StreamReader(ntwStream);
                Display(strmReader.ReadToEnd());
                socket.Close();
            }
        }

        static void Main(string[] args)
        {
            Console.Clear();
            Console.SetCursorPosition(0, 0);
            Console.WriteAscii("IP Upload S", Color.FromArgb(0, 255, 0));
            Console.WriteLine("By XiaoMingXD", Color.Yellow);
            if (args.Length == 0)
            {
                //检查是否有配置文件
                if (!File.Exists("config.ini"))
                    //如无则创建配置文件
                    GetPort();
                //在读取配置文件读入全局
                Port = ushort.Parse(Config.GetPrivateProfileString("Server", "Port", "23333", @".\config.ini"));
            }
            else
            {
                //利用ushort的0-65535检查 传入的端口是否正确
                try { Port = ushort.Parse(args[1]); }
                catch
                {
                    Console.WriteLine("WRONG PORT on argument. Should between 0-65535. Please try again.", Color.Red);
                    Environment.Exit(-1);
                }
            }
            Console.CursorVisible = false;
            Console.Write("Server Started On Port: ", Color.FromArgb(0, 255, 0));
            Console.Write(Port);
            Console.WriteLine(".", Color.FromArgb(0, 255, 0));
            Console.WriteLine();

            Thread thrListener = new Thread(new ThreadStart(Listen));
            thrListener.Start();
        }
    }
}
